import 'dart:ui';
import 'dart:math' as math;
import '../mixin/buttonSwitch.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import '../public/publicMethods.dart';

class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) {
    return orderBody();
  }
}

class orderBody extends StatefulWidget {
  @override
  _DatePickerExampleState createState() => new _DatePickerExampleState();
}

//整个移动的BOX
class moveBox extends AnimatedWidget {
  Widget child;
  bool state;
  double top;
  double left;

  moveBox({super.key, required Animation<double> animation,required this.child,required this.state,required this.top,required this.left})
      : super(listenable: animation);

  // Make the Tweens static because they don't change.

  Tween<Offset> _blurRadiusTween = Tween<Offset>(begin: Offset(50,50), end:Offset(400,400));


  @override
  Widget build(BuildContext context) {
    _blurRadiusTween = Tween<Offset>(begin: Offset(left,top), end:Offset(100,100));
    final animation = listenable as Animation<double>;
    return  Positioned(
          top: top,
          left:left,
          child: child,
    );

  }
}


/// RestorationProperty objects can be used because of RestorationMixin.
class _DatePickerExampleState extends State<orderBody>  with TickerProviderStateMixin,buttonSwitch{

  double getStatusBarHeight() {
    return MediaQuery.of(context).padding.top;
  }
  //移动BOX中心点
  Offset CenterPoint = Offset(0, 0);

  double rem = 1;

  bool moveBoxState = true;

  //移动父亲BOX尺寸
  double parentWidth = 400;
  double parentHeight = 400;

  bool TextFieldFocus = false;
  //移动BOX尺寸
  double moveBoxWidth = 700;
  double moveBoxHeight = 700;

  //移动BOX的坐标
  double xx = 0;
  double yy = 0;

  //APP图标大小
  double AppIconSize = 0;

  //拖动屏幕后松开手
  Offset moveBoxStartXY = Offset(0, 0);
  Offset moveBoxEndXY = Offset(0, 0);

  List<Map> searchHintList = [];
  String searchAppText = '';

  late Animation<double> animation;
  late AnimationController controller;

  late Animation<double> animationStartAPP;
  late AnimationController controllerStartAPP;


  late Animation<double> animationOpenApp;
  late AnimationController controllerOpenApp;

  List<List<Color>> colorsList = [
    [Color.fromRGBO(2, 126, 255, 1), Color.fromRGBO(26, 192, 224, 1)],
    [Color.fromRGBO(253, 15, 77, 1), Color.fromRGBO(253, 15, 77, 1)],
    [Color.fromRGBO(187, 187, 187, 1), Color.fromRGBO(61, 61, 61, 1)],
    [Color.fromRGBO(107, 254, 1, 1), Color.fromRGBO(17, 184, 7, 1)],
    [Color.fromRGBO(248, 189, 16, 1), Color.fromRGBO(251, 119, 5, 1)],

    [Color.fromRGBO(17, 166, 146, 1), Color.fromRGBO(8, 129, 130, 1)],
    [Color.fromRGBO(223, 254, 111, 1), Color.fromRGBO(159, 252, 11, 1)],
    [Color.fromRGBO(65, 203, 176, 1), Color.fromRGBO(0, 178, 172, 1)],
    [Color.fromRGBO(138, 61, 241, 1), Color.fromRGBO(167, 75, 233, 1)],
    [Color.fromRGBO(252, 62, 5, 1), Color.fromRGBO(187, 1, 0, 1)],
    [Color.fromRGBO(255 , 255, 255, 1), Color.fromRGBO(255, 255, 255, 1)],
  ];

  playAnimation(){
    (controller as AnimationController).reset();
    (controller as AnimationController).forward();
  }

  void getScreenResolution() async {
    controller = AnimationController(duration: const Duration(milliseconds: 300), vsync: this);

    animation = CurvedAnimation(parent: controller, curve: Curves.easeIn)..addListener(() {
      Tween<Offset> _blurRadiusTween = Tween<Offset>(begin: moveBoxStartXY,end:moveBoxEndXY);
      setState(() {
        yy =_blurRadiusTween.evaluate(animation).dy;
        xx = _blurRadiusTween.evaluate(animation).dx;
      });
      moveNarrowAPP();
    });

    controllerStartAPP = AnimationController(duration: const Duration(milliseconds: 1000), vsync: this);


    // 获取设备的分辨率
    var pixelRatio = await window.devicePixelRatio;
    var physicalSize = await window.physicalSize;

    // 计算分辨率宽度和高度
    var width = physicalSize.width / pixelRatio;
    var height = physicalSize.height / pixelRatio;


    for(double i =0;i<40;i++){
      appListData.add({
        "size":300*rem,"scale":1.0, "name":"APP"+i.toString(),
        "icon":'assets/icon/'+(i+1).toInt().toString()+'.png',
        "x":CenterPoint.dx,"y":CenterPoint.dy,
        "colorI": math.Random().nextInt(colorsList.length),
        "opacity":(1.0).toDouble(),
        "click":(){

          ScaffoldMessenger.of(context).removeCurrentSnackBar();

          ScaffoldMessenger.of(context).showSnackBar(SnackBar(
            content: Text(
                '功能暂未开放'),
          ));

        }
      });
    }

    //编写APP图标
    appListData[0] = {
      "size":300*rem,"scale":1.0, "name":"日报",
      "icon":'assets/icon/2.png',
      "opacity":(1.0).toDouble(),
      "x":CenterPoint.dx,"y":CenterPoint.dy,
      "colorI": 0,
      "click":(){
        this.openApp(0, '/daily');
      }
    };

    appListData[1] = {
      "size":300*rem,"scale":1.0, "name":"我的",
      "icon":'assets/icon/39.png',
      "opacity":(1.0).toDouble(),
      "x":CenterPoint.dx,"y":CenterPoint.dy,
      "colorI": 2,
      "click":(){
        this.openApp(1, '/user');
      }
    };


    List frequency = [6,6*2,6*3,6*4,6*5,6*6,6*7];
    int frequencyI = 0;
    double angleI = 0;

    for(double i =1;i<appListData.length;i++){
      angleI++;

      if(angleI == frequency[frequencyI]){
        frequencyI = frequencyI + 1;
        angleI = 0;
      }
    }

    setState(() {
      parentWidth = width;
      parentHeight = height - getStatusBarHeight();

      moveBoxWidth = 350*frequencyI*6*rem;
      moveBoxHeight = moveBoxWidth;

      xx = -(moveBoxWidth - parentWidth)/2;
      yy = -(moveBoxHeight - parentHeight)/2;
    });

    CenterPoint = Offset( moveBoxWidth/2 - (AppIconSize/2),moveBoxHeight/2-(AppIconSize/2));



    frequency = [6,6*2,6*3,6*4,6*5,6*6,6*7];
    frequencyI = 0;
    angleI = -1;

    for(double i =0;i<appListData.length;i++) {
      appListData[i.toInt()]['x'] = CenterPoint.dx;
      appListData[i.toInt()]['y'] = CenterPoint.dy;
    }

    animationStartAPP = CurvedAnimation(parent: controllerStartAPP, curve: Curves.easeInOut)..addListener(() {

      frequencyI = 0;
      angleI = -1;


      for(double i =0;i<appListData.length;i++){

        double angle = 360/frequency[frequencyI]*math.pi/180;
        double radius = 350*rem*(1+frequencyI);

        double left =  CenterPoint.dx;
        double top =  CenterPoint.dy;
        if(i != 0){
          left =  math.sin( (angle*angleI))*radius + CenterPoint.dx;
          top =  math.cos( (angle*angleI))*radius + CenterPoint.dy;
        }

        Tween<double> _XTween = Tween<double>(begin: CenterPoint.dx,end:left);
        Tween<double> _YTween = Tween<double>(begin: CenterPoint.dy,end:top);


        appListData[i.toInt()]['x'] = _XTween.evaluate(animationStartAPP);
        appListData[i.toInt()]['y'] = _YTween.evaluate(animationStartAPP);

        angleI++;

        if(angleI == frequency[frequencyI]){
          frequencyI = frequencyI + 1;
          angleI = 0;
        }



      }
      moveNarrowAPP();

    });


    Future.delayed(Duration(milliseconds: (800)), () {
      (controllerStartAPP as AnimationController).forward();
    });


  }

  getUserData() async{
    Map response = await ajax.postToken(path:'/competition-app/public/api/users/getUserData');

    if(response['statusCode'] == 200){
      Map<String, dynamic> userMap = jsonDecode(response['body']);

      if(userMap['code'] == 1){
        UserData = userMap['data'];
      }
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    getUserData();
    getScreenResolution();

  }

  List<Map> appListData = [];

  Widget AppIcon({required double top ,required double left}){
    return
      Positioned(
        top:top,
        left:left,
        child:
        Container(
          width: AppIconSize,
          height: AppIconSize,
          decoration: BoxDecoration(
            color: Colors.white,
            //border: Border.all(color: Colors.black87,width: 1.0,style: BorderStyle.solid),
            borderRadius: BorderRadius.circular(150*rem),
          ),
          child: ElevatedButton(
              onPressed: () {},
              child: const Text("普通按钮")
          ),
        )
      );
  }

  List<Widget> Apps(){
    List<Widget> apps = [];
    for(double i =0;i<appListData.length;i++){
      apps.add(
          Positioned(
              top:appListData[i.toInt()]['y'],
              left:appListData[i.toInt()]['x'],
              child:
                  Opacity(
                    opacity:appListData[i.toInt()]['opacity'],
                    child: Transform.scale(
                  scale:appListData[i.toInt()]['scale'], child: Container(
                  width: AppIconSize,
                  height: AppIconSize,
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: colorsList[appListData[i.toInt()]['colorI']], // 渐变的颜色
                    ),
                  //border: Border.all(color: Colors.black87,width: 1.0,style: BorderStyle.solid),
                  borderRadius: BorderRadius.circular(150*rem),
                ),
                child: Stack(
                  alignment:Alignment.center,
                  children: [
                    Container(
                      margin: EdgeInsets.fromLTRB(0, 0, 0, 70*rem),
                        width: AppIconSize/2.5,
                        height: AppIconSize/2.5,
                        child:Image.asset(
                            appListData[i.toInt()]['icon']
                        )
                    ),

                    Container(
                      alignment: Alignment.center,
                        margin: EdgeInsets.fromLTRB(0, 170*rem, 0, 0),
                        width: AppIconSize,
                        height: AppIconSize,
                        child:Text(appListData[i.toInt()]['name'],style: TextStyle(shadows: [

                          Shadow(
                            color: Colors.black,
                            offset: Offset(1,1),
                            blurRadius: 5.0,
                          ),
                        ],fontSize: 46*rem, color: Colors.white),)
                    ),

                    Container(
                      width: AppIconSize,
                      height: AppIconSize,
                      child: TextButton (
                          style: ButtonStyle(
                              backgroundColor: MaterialStateProperty.all(Color.fromRGBO(0, 0, 0, 0)),
                            elevation: MaterialStateProperty.all(20),
                            foregroundColor:
                              MaterialStateProperty.all(Colors.white),
                              ),
                          onPressed: appListData[i.toInt()]['click'],
                          child: Text('')
                      )),

                  ],
                )
              )
          )

          )
          ));

    }

    return apps;
  }

  closeApp(int index){
    setButtonState( key:'login', switchBool:true);
    (controllerOpenApp as AnimationController).reverse();

  }

  void openApp(int index,String path){
    if(getButtonState( key:'login')) {
      setButtonState( key:'login', switchBool:false);
      ScaffoldMessenger.of(context).removeCurrentSnackBar();

      controllerOpenApp = AnimationController(duration: const Duration(milliseconds: 300), vsync: this);

      animationOpenApp =
      CurvedAnimation(parent: controllerOpenApp, curve: Curves.easeIn)
        ..addListener(() {
          Tween<double> _blurRadiusTween = Tween<double>(begin: 1, end: 10);
          Tween<double> _opacity = Tween<double>(begin: 1, end: 0);

          setState(() {
            for (int i = 0; i < appListData.length; i++) {
              appListData[i]['opacity'] = _opacity.evaluate(animationOpenApp);
            }
            appListData[index]['scale'] =
                _blurRadiusTween.evaluate(animationOpenApp);
            appListData[index]['opacity'] = (1).toDouble();
          });
        });
      (controllerOpenApp as AnimationController).reset();
      (controllerOpenApp as AnimationController).forward();

      Future.delayed(Duration(milliseconds: 200), () {
        Navigator.pushNamed(context,path).then((v) {
          Future.delayed(Duration(milliseconds: 100), () {
            closeApp(index);
          });
        });
      });
    }
  }

  //镜头拖动的时候位移缩放
  moveNarrowAPP(){
    for(int i =0;i<appListData.length;i++){
      double xDistance = ((-appListData[i]['x']-AppIconSize/2) - (xx - parentWidth/2)).abs();
      double yDistance = ((-appListData[i]['y']-AppIconSize/2) - (yy - parentHeight/2)).abs();

      double size = 1;

      double sizeY = 1;
      if(xDistance > parentWidth/2){
        size = 0;
      }else{
        size = 2- (xDistance/(parentWidth/2))*2;
        size = size>1?1:size;
      }

      if(yDistance > parentHeight/2){
        sizeY = 0;
      }else{
        sizeY = 2- (yDistance/(parentHeight/2))*2;
        sizeY = sizeY>1?1:sizeY;
      }

      if(sizeY < size){
        size  = sizeY;
      }

      setState(() {
        appListData[i.toInt()]['scale'] = size;
      });
    }
  }

  //寻找最近中心点的图标
  searchingRecently(){
    int minI = 0;
    double minDistance = 999999;

    //print((xx.abs()+moveBoxWidth/2).abs());
    for(int i =0;i<appListData.length;i++){

      double distance = ((-appListData[i]['x']-AppIconSize/2) - (xx - parentWidth/2)).abs();

      distance = distance + ((-appListData[i]['y']-AppIconSize/2) - (yy - parentHeight/2)).abs();


      if(distance <= minDistance){
        minDistance =  distance;
        minI = i;
      }
    }

    setState(() {
      moveBoxStartXY = Offset(xx, yy);
      moveBoxEndXY = Offset(-appListData[minI]['x']+parentWidth/2-AppIconSize/2,-appListData[minI]['y']+parentHeight/2-AppIconSize/2);
      moveBoxState = false;
    });
    playAnimation();

  }

  searchApp(String text){

    double number = 0;
    searchAppText = text;
    searchHintList = [];
    if(text != ''){
      for(int i =0;i<appListData.length;i++){
        if(appListData[i]['name'].contains(text) && number<4){
          searchHintList.add({
            "index":i,
            "name":appListData[i]['name']
          });
          number++;
        }
      }
    }

    setState(() {});
  }

  searchAppButton(){
    bool iss = true;
    for(int i =0;i<appListData.length;i++){
      if(appListData[i]['name'] == searchAppText){
        searchAppMove(i);
        iss = false;
      }
    }
    if(iss){
      ScaffoldMessenger.of(context).removeCurrentSnackBar();

      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text(
            '无法找到APP'),
      ));
    }


  }

  searchAppMove(int index){
    ScaffoldMessenger.of(context).removeCurrentSnackBar();
    TextFieldFocus = false;
    FocusScope.of(context).requestFocus(FocusNode());
    setState(() {
      moveBoxStartXY = Offset(xx, yy);
      moveBoxEndXY = Offset(-appListData[index]['x']+parentWidth/2-AppIconSize/2,-appListData[index]['y']+parentHeight/2-AppIconSize/2);
      moveBoxState = false;
    });
    playAnimation();
  }


  List<Widget> searchHint(){
    List<Widget> list = [];


    for(int i=0;i<searchHintList.length;i++){
      list.add(
        Container(
          width: 999,
          height: 180*rem,
          child:
          ElevatedButton(
              style: ButtonStyle(
                backgroundColor:MaterialStateProperty.all(Color.fromRGBO(255  , 255 , 255, 1)),
                foregroundColor: MaterialStateProperty.all(Colors.black),
                shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(8*rem))),

            ),
              onPressed: () {
                searchAppMove(searchHintList[i]['index']);
              },
              child:Text(searchHintList[i]['name'],style: TextStyle( fontSize: 48*rem),),
          )
        )
      );
    }

    return list;
  }

  @override
  Widget build(BuildContext context) {
    rem =  MediaQuery.of(context).size.width/1080;
    AppIconSize = 300*rem;

    return Scaffold(
      body: Center(
          child:
          Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/bg3.jpg'),
                fit: BoxFit.cover,
              ),
            ),
            child: Container(
                margin: EdgeInsets.fromLTRB(0, getStatusBarHeight(), 0, 0),
                child:Stack(
                  children: [
                    GestureDetector(
                        onPanDown: (details) {
                          if(getButtonState( key:'login')) {
                            setState(() {
                              moveBoxState = true;
                              TextFieldFocus = false;
                            });
                            controller.stop();
                            FocusScope.of(context).requestFocus(FocusNode());
                          }
                        },
                        onPanEnd: (details){
                          if(getButtonState( key:'login')) {
                            searchingRecently();
                          }
                        },
                        onPanUpdate: (details) {
                          if(getButtonState( key:'login')) {
                            setState(() {
                              xx += details.delta.dx;
                              yy += details.delta.dy;
                            });
                            moveNarrowAPP();
                          }
                        },
                        child: Stack(
                          children: [
                            Container(
                                width:parentWidth,
                                height: parentHeight,
                            ),
                            moveBox(
                                top: yy,
                                left:xx,
                                animation: animation,
                                state: moveBoxState,
                                child:Stack(
                                  alignment: Alignment.center,
                                  children: [
                                    Container(
                                        width:moveBoxWidth,
                                        height:moveBoxHeight,
                                        color: Color.fromRGBO(0, 0, 0, 0)
                                    ),
                                    ...Apps()

                                  ],
                                )
                            )
                          ],
                        )
                    )
                    ,
                    AnimatedContainer(
                      duration:  Duration(milliseconds:300 ),
                      width: TextFieldFocus?1060*rem:400*rem,
                      padding: EdgeInsets.all(30*rem),
                      child: Stack(
                        alignment: Alignment.centerRight,
                        children: [

                          Column(
                            children: [
                              Stack(
                              alignment: Alignment.centerRight,
                              children: [
                                TextField(
                                  onChanged: (text) {
                                    searchApp(text);
                                  },
                                  onTap: (){
                                    setState(() {
                                      TextFieldFocus = true;
                                    });
                                  },
                                  keyboardType:TextInputType.emailAddress,
                                  decoration: InputDecoration(
                                    disabledBorder: OutlineInputBorder(
                                      borderSide: BorderSide.none,
                                      //    borderRadius: BorderRadius.circular(8.w)
                                    ),
                                    enabledBorder: OutlineInputBorder(borderSide: BorderSide.none),
                                    focusedBorder: OutlineInputBorder(borderSide: BorderSide.none),
                                    border: OutlineInputBorder(borderSide: BorderSide.none),
                                    filled: true,
                                    fillColor: TextFieldFocus?Colors.white:Color.fromRGBO(0, 0, 0, 0),
                                    hintText: '搜索',
                                    hintStyle: TextStyle(color: TextFieldFocus?Colors.grey:Colors.white),
                                    prefixIcon: Icon(Icons.search,color: TextFieldFocus?Color.fromRGBO(117,117,117,1):Color.fromRGBO(255  ,255,255,1)),
                                  ),
                                ),
                                Visibility(
                                    visible:TextFieldFocus,
                                    child: Container(
                                        child: IconButton(
                                          icon: Icon(Icons.done),
                                          onPressed: searchAppButton,
                                        )
                                    )),
                              ]
                              ),
                              Visibility(
                                  visible:TextFieldFocus,
                                  child:  Column(
                                    children:searchHint(),
                                  )),

                            ],
                          ),




                        ],
                      )
                    )

                  ],
                )
            ),
          )
      ),
    );
  }
}



